<template>
  <div class="knowledge-component">
    <!-- 左侧知识库列表 -->
    <div class="knowledge-sidebar">
      <div class="sidebar-header">
        <h2>知识库列表</h2>
      </div>

      <div class="sidebar-content">
        <div class="search-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索知识库..."
            size="small"
            clearable
            @input="handleSearch"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="5" animated />
        </div>

        <div v-else-if="knowledgeBases.length > 0" class="knowledge-list">
          <div
            v-for="knowledgeBase in knowledgeBases"
            :key="knowledgeBase.id"
            class="knowledge-item"
            :class="{ active: currentKnowledgeBase?.id === knowledgeBase.id }"
            @click="selectKnowledgeBase(knowledgeBase)"
          >
            <div class="knowledge-info">
              <div class="knowledge-title">
                <div class="title-row">
                  <span class="knowledge-name">{{ knowledgeBase.name }}</span>
                  <el-tag
                    size="small"
                    :type="knowledgeBase.status === 1 ? 'success' : 'danger'"
                  >
                    {{ knowledgeBase.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </div>

              </div>

              <div class="knowledge-stats">
                <span class="stat-item">
                  <el-icon><Document /></el-icon>
                  {{ knowledgeBase.item_count || 0 }} 条目
                </span>
                <span class="update-time">
                  {{ formatTime(knowledgeBase.updated_at) }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="empty-state">
          <div class="empty-icon">
            <el-icon><Collection /></el-icon>
          </div>
          <div class="empty-text">暂无知识库</div>
          <div class="empty-description">
            {{ searchQuery ? '没有找到匹配的知识库' : '系统中还没有可用的知识库' }}
          </div>
        </div>

        <!-- 数据统计 -->
        <div class="stats-container" v-if="total > 0">
          <div class="stats-text">
            共 {{ total }} 个知识库
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧知识库详情 -->
    <div class="knowledge-detail">
      <KnowledgeDetail
        v-if="currentKnowledgeBase"
        :current-knowledge-base="currentKnowledgeBase"
        :is-dark-mode="isDarkMode"
      />
      <div v-else class="empty-detail">
        <el-empty description="请选择一个知识库" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Document, Collection } from '@element-plus/icons-vue'
import KnowledgeDetail from '../components/layout/KnowledgeDetail.vue'
import { getKnowledgeBases } from '../api/knowledge'
import { useRoute } from 'vue-router'

const route = useRoute()

defineProps({
  isDarkMode: {
    type: Boolean,
    default: false,
  },
})

// 知识库列表
const knowledgeBases = ref([])
const currentKnowledgeBase = ref(null)
const loading = ref(false)

// 数据统计
const total = ref(0)

// 搜索
const searchQuery = ref('')

// 搜索防抖定时器
let searchTimer = null



// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return time.toLocaleDateString('zh-CN')
  }
}

// 根据ID选择知识库
const selectKnowledgeBaseById = (knowledgeBaseId) => {
  const knowledgeBase = knowledgeBases.value.find((kb) => kb.id === parseInt(knowledgeBaseId))
  if (knowledgeBase) {
    currentKnowledgeBase.value = knowledgeBase
  }
}

// 获取知识库列表
const fetchKnowledgeBases = async () => {
  try {
    loading.value = true

    const params = {
      status_filter: 1, // 只获取启用的知识库
    }

    if (searchQuery.value.trim()) {
      params.search = searchQuery.value.trim()
    }

    const response = await getKnowledgeBases(params)

    if (response.success) {
      knowledgeBases.value = response.data || []
      total.value = response.total || 0

      // 从路由参数中获取知识库ID
      const knowledgeBaseId = route.params.id
      if (knowledgeBaseId) {
        selectKnowledgeBaseById(knowledgeBaseId)
      } else if (knowledgeBases.value.length > 0) {
        // 如果没有指定ID，默认选择第一个
        currentKnowledgeBase.value = knowledgeBases.value[0]
      }
    } else {
      ElMessage.error('获取知识库列表失败')
    }
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    ElMessage.error('获取知识库列表失败')
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId && knowledgeBases.value.length > 0) {
      selectKnowledgeBaseById(newId)
    }
  },
)

// 选择知识库
const selectKnowledgeBase = (knowledgeBase) => {
  currentKnowledgeBase.value = knowledgeBase
}

// 处理搜索
const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    fetchKnowledgeBases()
  }, 300)
}



onMounted(() => {
  fetchKnowledgeBases()
})
</script>

<style scoped>
.knowledge-component {
  height: 100vh;
  width: 100%;
  display: flex;
  color: var(--el-text-color-primary);
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* 左侧知识库列表样式 */
.knowledge-sidebar {
  width: 240px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  box-shadow: var(--app-shadow-hover);
  height: 100%;
  overflow: hidden;
}

.sidebar-header {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  box-shadow: var(--app-shadow-hover);
  flex-direction: column;
  align-items: stretch;
}

.sidebar-header h2 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--app-text-primary);
}

.header-actions {
  margin-bottom: 0;
}



.sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 搜索框容器样式 */
.search-container {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(var(--el-color-primary-rgb), 0.2);
}

.loading-state {
  padding: 16px;
  margin-top: 0;
}

.knowledge-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.knowledge-item {
  background: var(--app-bg-primary, #ffffff);
  border: 1px solid var(--app-border-color, #e4e7ed);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.knowledge-item:hover {
  border-color: var(--app-primary, #409eff);
  box-shadow: var(--app-shadow-hover, 0 2px 8px rgba(0, 0, 0, 0.1));
}

.knowledge-item.active {
  border-color: var(--app-primary, #409eff);
  background: var(--app-primary-light, #ecf5ff);
}

.knowledge-info {
  width: 100%;
}

.knowledge-title {
  margin-bottom: 8px;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.knowledge-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--app-text-primary, #303133);
  flex: 1;
  margin-right: 8px;
  line-height: 1.4;
}

.knowledge-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: var(--app-text-secondary, #909399);
}

.category-tag {
  background: var(--app-bg-tag, #f4f4f5);
  padding: 2px 6px;
  border-radius: 4px;
}

.knowledge-description {
  color: var(--app-text-secondary, #606266);
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.knowledge-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--app-text-secondary, #909399);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.update-time {
  white-space: nowrap;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  text-align: center;
  flex: 1;
  margin-top: 0;
}

.empty-icon {
  font-size: 48px;
  color: var(--app-text-placeholder, #c0c4cc);
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: var(--app-text-primary, #303133);
  margin-bottom: 8px;
}

.empty-description {
  font-size: 14px;
  color: var(--app-text-secondary, #909399);
}

.stats-container {
  padding: 12px 16px;
  border-top: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
  text-align: center;
  flex-shrink: 0;
}

.stats-text {
  font-size: 14px;
  color: var(--app-text-secondary, #909399);
}

/* 右侧详情样式 */
.knowledge-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.empty-detail {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: var(--app-bg-secondary, #ffffff);
}

/* 暗黑模式适配 */
.dark .knowledge-component {
  background: var(--el-bg-color-page);
}

.dark .knowledge-sidebar,
.dark .empty-detail {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

.dark .sidebar-header {
  border-color: var(--el-border-color);
}

.dark .knowledge-item {
  background: var(--el-bg-color-page);
  border-color: var(--el-border-color);
}

.dark .knowledge-item:hover {
  border-color: var(--el-color-primary);
}

.dark .knowledge-item.active {
  background: var(--el-color-primary-light-9);
}

.dark .stats-container {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

.dark .category-tag {
  background: var(--el-fill-color-light);
}
</style>
